#include "datamanagerwidget.h"
#include "tablemodel.h"

#include <QDesktopWidget>
#include <QAction>
#include <QDockWidget>
#include <QVBoxLayout>
#include <QToolBar>

DataManagerWidget::DataManagerWidget(QWidget *parent) :
    QDockWidget(parent)
{
    tabWidget.setTabsClosable(true);
    connect(&tabWidget, SIGNAL(tabCloseRequested(int)),
            this, SLOT(closeTabView(int)) );
    setWidget(&tabWidget);
    setAllowedAreas(Qt::LeftDockWidgetArea |
                    Qt::RightDockWidgetArea);
    setMinimumHeight(parent->height()/3);
    setFeatures(QDockWidget::DockWidgetFloatable |
                QDockWidget::DockWidgetMovable);
    setObjectName(tr("Data"));
    setWindowTitle(tr("Data"));

//    setStyleSheet("border: 3px solid transparent; padding: 0px;");
//    QToolBar* qw = new QToolBar();
//    qw->addAction(tr("Close"));
//    setTitleBarWidget(qw);
}



DataManagerWidget::~DataManagerWidget()
{
//    delete tabWidget; //parent is this, needn't
}

//void DataManagerWidget::closeEvent(QCloseEvent *event)
//{
//    if(event->type() == QEvent::Close)
//    {
//        emit dataManagerClosing();
//        event->ignore();
//        this->hide();
//    }
//}

void DataManagerWidget::addTabView(GSData* varData)
{
    QString varname;
    varname = varData->name;
    //check for duplicates
    for(int i=0; i<tabName.count(); i++)
    {
        if(varname == tabName.at(i)) //Have already exist
        {
            tabWidget.setCurrentIndex(i);
            return;
        }
    }

    //New TabView
    QTableView* tabView = new QTableView(this);
    tabViewSet.append(tabView);
    tabWidget.addTab(tabView, varname);
    tabName.append(varname); //store variable name
    tabWidget.setCurrentIndex(tabWidget.count()-1);

    TableModel* table = new TableModel(varData,this);
    tabView->setModel(table);
    tableModelSet.append(table);
}

void DataManagerWidget::closeTabView(int index)
{
    tabWidget.removeTab(index);
    delete tabViewSet.at(index);
    tabViewSet.removeAt(index);
    delete tableModelSet.at(index);
    tableModelSet.removeAt(index);
    tabName.removeAt(index);
}

void DataManagerWidget::deleteTabView(QString name)
{
    for(int i=0; i<tabName.count(); i++)
    {
        if(tabName.at(i) == name)
        {
            closeTabView(i);
            break;
        }
    }
}
